/*
 * fetch.c
 *
 * Copyright (C) 2011-2012 Dan Reidy <dubkat@ratbox.org>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to:
 *
 *       The Free Software Foundation, Inc.
 *       59 Temple Place - Suite 330
 *       Boston, MA  02111-1307, USA.
 *
 *
 *  $Id: fetch.c 21 2012-03-26 03:59:17Z dubkat $
 */

#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <err.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>

/* "BSIZE" is the size of the buffer we use to read from the socket. */

#define BSIZE 0x1000

#ifndef _GNU_SOURCE
#	define _GNU_SOURCE
#endif

int fetch(const char *qurve_stamp);
static void get_page(int s, const char *host, const char *page);

/* Get the web page and print it to standard output. */

static void
get_page(int s, const char *host, const char *page)
{
	char *msg;
	const char *format = "GET /%s HTTP/1.0\r\nHost: %s\r\nUser-Agent: ratbox-montior\r\n\r\n";

	asprintf(&msg, format, page, host);
	send(s, msg, strlen(msg), 0);

	while(1)
	{
		int bytes;
		char buf[BSIZE + 10];
		bytes = recvfrom(s, buf, BSIZE, 0, 0, 0);
		if(bytes == -1)
		{
			fprintf(stderr, "%s\n", strerror(errno));
			exit(1);
		}
		buf[bytes] = '\0';
		printf("%s", buf);
		if(bytes == 0)
		{
			break;
		}
	}
	free(msg);
}

int
fetch(const char *qurve_stamp)
{
	struct addrinfo hints, *res, *res0;
	int error;
	int s;
	const char *host = "www.efnet.org";

	memset(&hints, 0, sizeof(hints));

	hints.ai_family = PF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	error = getaddrinfo(host, "http", &hints, &res0);

	if(error)
	{
		fprintf(stderr, "%s\n", gai_strerror(error));
		exit(1);
	}
	s = -1;
	for(res = res0; res; res = res->ai_next)
	{
		s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
		if(s < 0)
		{
			fprintf(stderr, "socket: %s\n", strerror(errno));
			exit(1);
		}

		if(connect(s, res->ai_addr, res->ai_addrlen) < 0)
		{
			fprintf(stderr, "connect: %s\n", strerror(errno));
			close(s);
			exit(1);
		}
		break;
	}
	if(s != -1)
	{
		get_page(s, host, "klines/");
	}
	freeaddrinfo(res0);
	return 0;
}
